package com.mc.read.pcApi.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mc.read.common.constant.ApplicationValues;
import com.mc.read.common.constant.Constants;
import com.mc.read.common.emun.ServiceCodeEnum;
import com.mc.read.common.exception.ServiceException;
import com.mc.read.common.util.HttpRequestor;
import com.mc.read.common.util.PrimarykeyUtil;
import com.mc.read.common.util.SmsUtil;
import com.mc.read.dao.mapper.LoginrecordMapper;
import com.mc.read.dao.mapper.PhonecodeMapper;
import com.mc.read.dao.mapper.UserinformationMapper;
import com.mc.read.dao.mapper.UserinformationdetMapper;
import com.mc.read.dao.models.*;
import com.mc.read.dao.vo.LoginRequest;
import com.mc.read.vo.request.BaseRequest;
import com.mc.read.vo.respose.BaseRespose;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
public class LoginService {
    @Autowired
    UserinformationMapper userinformationMapper;
    @Autowired
    PhonecodeMapper phonecodeMapper;
    @Autowired
    UserinformationdetMapper userinformationdetMapper;
    @Autowired
    LoginrecordMapper loginrecordMapper;

    /**
     * @Author:LiuHao
     * @Date:14:31 2019/5/30
     * 用户登录login
     **/
    public BaseRespose login(BaseRequest baseRequest) {
        log.info("用户登录,参数为{}", JSON.toJSONString(baseRequest));
        BaseRespose baseRespose = new BaseRespose();
        LoginRequest loginRequest = null;
        try {
            loginRequest = JSON.parseObject(JSON.toJSONString(baseRequest.getRequestString()), LoginRequest.class);
        } catch (Exception e) {
            throw new ServiceException(ServiceCodeEnum.INFO_IS_FAIL, JSON.toJSONString(baseRequest));
        }
        Date lastTime = null;
        Userinformation userinformation = null;
        //电话登录
        if (!ObjectUtils.isEmpty(loginRequest.getPhone())) {
            if (ObjectUtils.isEmpty(loginRequest.getCode())) {
                throw new ServiceException(202010, "请输入手机验证码", JSON.toJSONString(baseRequest));
            }
//            if(loginRequest.getCode().equals("8888")){
//
//            }else {
            Phonecode phonecode = phonecodeMapper.selectLastLogin(loginRequest.getPhone());
            if (ObjectUtils.isEmpty(phonecode) || !loginRequest.getCode().equals(phonecode.getCode())) {
                throw new ServiceException(203020, "验证码错误，请输入正确的验证码", JSON.toJSONString(baseRequest));
            }

            if (phonecode.getUsed() != 0) {
                throw new ServiceException(203020, "该验证码已使用过或已失效，请重新发送新的验证码");
            }
            if (new Date().getTime() > phonecode.getExpirationtime().getTime()) {
                throw new ServiceException(203020, "验证码以过期，请重新发送");
            }
            phonecode.setUsed(1);
            phonecodeMapper.updateByPrimaryKeySelective(phonecode);
//            }

            UserinformationExample example = new UserinformationExample();
            example.createCriteria().andPhoneEqualTo(loginRequest.getPhone()).andStausEqualTo(1);
            List<Userinformation> userinformationLis = userinformationMapper.selectByExample(example);
            if (userinformationLis.size() < 1) {
                userinformation = new Userinformation();
                userinformation.setPhone(loginRequest.getPhone());
                userinformation.setCreatedate(new Date());
                userinformation.setStaus(1);
                userinformationMapper.insert(userinformation);
                userinformationLis = userinformationMapper.selectByExample(example);
                userinformation = userinformationLis.get(0);
                Userinformationdet userinformationdet = new Userinformationdet();
                userinformationdet.setUserid(userinformation.getUserid());
                userinformationdet.setName(loginRequest.getPhone());
                userinformationdetMapper.insertSelective(userinformationdet);

//                redSuccessSms(loginRequest.getPhone());


            } else {
                userinformation = userinformationLis.get(0);
                lastTime = userinformation.getLastlogintime();
            }
        } else {
            if (ObjectUtils.isEmpty(loginRequest.getCode())) {
                throw new ServiceException(202010, "请输入微信code", JSON.toJSONString(baseRequest));
            }
            String code = loginRequest.getCode();
            String appid = ApplicationValues.getAppid();
            String secret = ApplicationValues.getAPPSECRET();
            String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";
            //第一次请求 获取access_token 和 openid
            String oppid = null;
            JSONObject oppidObj = null;
            try {
                oppid = new HttpRequestor().doGet(requestUrl);
                oppidObj = JSON.parseObject(oppid);
                log.info("微信登录返回：{}", oppid);
            } catch (Exception e) {
                e.printStackTrace();
                throw new ServiceException(203020, "获取微信信息错误");
            }
            if (!ObjectUtils.isEmpty(oppidObj.get("errcode"))) {
                throw new ServiceException(203020, "获取微信信息错误");
            }
//            String access_token = (String) oppidObj.get("access_token");
            String openid = (String) oppidObj.get("openid");
            if (ObjectUtils.isEmpty(oppid)) {
                throw new ServiceException(203020, "获取微信信息错误");
            }
            UserinformationExample example = new UserinformationExample();
            example.createCriteria().andOpenidEqualTo(openid).andStausEqualTo(1);
            List<Userinformation> userinformationLis = userinformationMapper.selectByExample(example);
            if (userinformationLis.size() < 1) {
                userinformation = new Userinformation();
                userinformation.setOpenid(openid);
                userinformation.setCreatedate(new Date());
                userinformation.setStaus(1);
                userinformationMapper.insert(userinformation);
                userinformationLis = userinformationMapper.selectByExample(example);
                userinformation = userinformationLis.get(0);
                Userinformationdet userinformationdet = new Userinformationdet();
                userinformationdet.setUserid(userinformation.getUserid());
                userinformationdet.setName(loginRequest.getCode());
                userinformationdetMapper.insertSelective(userinformationdet);
            } else {
                userinformation = userinformationLis.get(0);
                lastTime = userinformation.getLastlogintime();
            }
//            String requestUrl2 = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid+"&lang=zh_CN";
//            String userInfoStr = new HttpRequestor().doGet(requestUrl2);
//            JSONObject wxUserInfo =JSONObject.fromObject(userInfoStr);
        }
        userinformation.setToken(PrimarykeyUtil.queryPrimarykey30());

        userinformation.setLastlogintime(new Date());
        userinformationMapper.updateByPrimaryKeySelective(userinformation);
        if (!ObjectUtils.isEmpty(lastTime)) {
            userinformation.setLastlogintime(lastTime);
        }
        Loginrecord loginrecord = new Loginrecord();
        loginrecord.setUserid(userinformation.getUserid());
        loginrecord.setCreatedate(new Date());
        loginrecordMapper.insertSelective(loginrecord);
        baseRespose.setReturnString(userinformation);
        return baseRespose;
    }

    /**
     * @Author:LiuHao
     * @Date:16:50 2019/5/30
     * 发送登录验证码 sendLoginCode
     **/
    public BaseRespose sendLoginCode(BaseRequest baseRequest) {
        log.info("发送登录验证码,参数为{}", JSON.toJSONString(baseRequest));
        BaseRespose baseRespose = new BaseRespose();
        LoginRequest loginRequest = null;
        try {
            loginRequest = JSON.parseObject(JSON.toJSONString(baseRequest.getRequestString()), LoginRequest.class);
        } catch (Exception e) {
            throw new ServiceException(ServiceCodeEnum.INFO_IS_FAIL, JSON.toJSONString(baseRequest));
        }
        if (ObjectUtils.isEmpty(loginRequest.getPhone())) {
            throw new ServiceException(203020, "手机号不能为空", JSON.toJSONString(baseRequest));
        }
        String code = SmsUtil.getCode();
        SmsUtil.sendSms(loginRequest.getPhone(), code);
        Phonecode phonecode = new Phonecode();
        phonecode.setCode(code);
        phonecode.setPhone(loginRequest.getPhone());
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.MINUTE, Constants.PHONE_CODE_TIME);
        phonecode.setExpirationtime(c.getTime());
        phonecode.setUsed(0);
        phonecode.setUsetype(1);
        phonecodeMapper.insertSelective(phonecode);
        baseRespose.setReturnString(" ");
        return baseRespose;
    }

    /**
     * @Author:LiuHao
     * @Date:15:24 2019/5/31
     * 注册成功发送短信 redSuccessSms
     **/
    public void redSuccessSms(String tel) {
        int count = userinformationMapper.countByExample(null) + Constants.REG_SUM;
        SmsUtil.sendSmsForRegSuccess(tel, String.valueOf(count));
    }

    /**
     * @Author:LiuHao
     * @Date:12:02 2019/7/3
     * 查询是否登录了 selectIsLogin
     **/
    public BaseRespose selectIsLogin(BaseRequest baseRequest) {
        log.info("查询是否登录了,参数为{}", JSON.toJSONString(baseRequest));

        BaseRespose baseRespose = new BaseRespose();

        if (ObjectUtils.isEmpty(baseRequest.getUserId()) || ObjectUtils.isEmpty(baseRequest.getToken())) {
            throw new ServiceException(203020, "请重新登录", JSON.toJSONString(baseRequest));
        }
        Userinformation userinformation1 = userinformationMapper.selectByPrimaryKey(baseRequest.getUserId());
        if (ObjectUtils.isEmpty(userinformation1)) {
            throw new ServiceException(203020, "请重新登录", JSON.toJSONString(baseRequest));
        }
        if(!baseRequest.getToken().equals(userinformation1.getToken())){
            throw new ServiceException(203020, "请重新登录", JSON.toJSONString(baseRequest));
        }
        baseRespose.setReturnString(" ");
        return baseRespose;
    }

}
